package com.jacob.androidframe.util;

import java.io.File;

import com.jacob.androidframe.controls.ApplicationExtend;

import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;

public class UtilFile
{
	/**
	 * 传入目录名称，本方法会在设备的默认外置存储中创建该目录。并返回其File对象。
	 * 若传入null、空字符串或非法路径，则返回默认外置存储的根目录。
	 * 若调用本方法时，外置存储不可用，则返回null。
	 * 
	 * @param pDirectoryName
	 *            目录名称，必须是相对路径。例如："新建文件夹"或"一级目录" + File.separator + "二级目录"。
	 * @return 该目录的File对象。
	 */
	public static File getExternalStorageDirectory(String pDirectoryName)
	{
		File _Directory = null;
		
		if (TextUtils.isEmpty(pDirectoryName)) {
			pDirectoryName = "";
		}
		
		if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
			String _DirectoryPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + pDirectoryName;
			_Directory = new File(_DirectoryPath);
			if (_Directory.isDirectory()) {
				if (!_Directory.exists()) {
					if (!_Directory.mkdirs()) {
						_Directory = Environment.getExternalStorageDirectory();
					}
				}
			} else {
				_Directory = Environment.getExternalStorageDirectory();
			}
		} else {
			_Directory = null;
		}
		
		return _Directory;
	}
	
	/**
	 * 得到程序的缓存目录。
	 * <p>
	 * 如果程序有读写外置缓存目录的权限，并且外置存储当前可用，则返回外置缓存目录；否则返回内置缓存目录。
	 * 
	 * @return
	 */
	public static File getCacheDir()
	{
		File _CacheDir = null;
		
		boolean _MediaIsMounted = Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
		boolean _hasExternalCacheDirPermission = UtilPermission.hasExternalStoragePermission(null) || Build.VERSION.SDK_INT >= 19;
		
		if ( _MediaIsMounted && _hasExternalCacheDirPermission) {
			_CacheDir = ApplicationExtend.getInstance().getExternalCacheDir();
		}
		
		if (_CacheDir == null) {
			_CacheDir = ApplicationExtend.getInstance().getCacheDir();
		}
		
		if (_CacheDir == null) {
			throw new RuntimeException("Can't get cache dir... This is not supposed to happen...");
		}
		
		return _CacheDir;
	}

}
